package com.wen.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wen.pojo.CurrentUser;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "wen";
    //token中存放用户id对应的名字
    private static final String CLAIM_NAME_USERID = "CLAIM_NAME_USERID";
    //token中存放用户名对应的名字
    private static final String CLAIM_NAME_USERCODE = "CLAIM_NAME_USERCODE";
    //token中存放用户真实姓名对应的名字
    private static final String CLAIM_NAME_USERNAME = "CLAIM_NAME_USERNAME";

    //接收业务数据,生成token并返回
    public static String genToken(CurrentUser currentUser) {
        return JWT.create()
                .withClaim(CLAIM_NAME_USERID, currentUser.getUserId())
                .withClaim(CLAIM_NAME_USERCODE, currentUser.getUserCode())
                .withClaim(CLAIM_NAME_USERNAME, currentUser.getUserName())
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
                .sign(Algorithm.HMAC256(KEY));
    }

	//接收token,验证token,并返回业务数据
    public static CurrentUser parseToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(KEY))
                            .build()
                            .verify(token);
        CurrentUser currentUser = new CurrentUser();
        currentUser.setUserId(jwt.getClaim(CLAIM_NAME_USERID).asInt());
        currentUser.setUserCode(jwt.getClaim(CLAIM_NAME_USERCODE).asString());
        currentUser.setUserName(jwt.getClaim(CLAIM_NAME_USERNAME).asString());

        return currentUser;
    }

}
